package light.head.dao.oa;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import light.head.constant.Parm;
import light.head.enm.RESULT;
import light.head.framework.base.BaseDAO;
import light.head.framework.entity.PageBean;
import light.head.model.ContractType;

@Service
public class ContractTypeDAO extends BaseDAO<ContractType, Integer>{
	
	private final static String sql_findAll = "FROM ContractType c WHERE c.deleted = 0 AND c.oc = ? ";
	
	public RESULT findByMap(Map<String, String> map, PageBean pb) {
		StringBuffer hql = new StringBuffer(" FROM ContractType c WHERE 1=1");
		List<Object> list = null;
		if(null != map) {
			list = new ArrayList<Object>();
			String name = map.get(Parm.NAME);
			String oc = map.get(Parm.OC);
			if(isNotNull(name)) {
				hql.append(" AND c.name = ?");
				list.add("%" + name + "%");
			}if(isNotNull(oc)) {
				hql.append(" AND c.oc = ?");
				list.add(Integer.parseInt(oc));
			}
			
			hql.append(" AND (c.deleted = 0 OR c.deleted is null)");
			hql.append(" ORDER BY c.code DESC");
		}
		
		if(findToPageBean(hql.toString(), pb, list) == RESULT.SUCCESS)
			return RESULT.SUCCESS;
			
		return RESULT.ERROR;
	}
	
	public RESULT update(ContractType cType) {
		if(null == cType || null == cType.getCode()) {
			return RESULT.PARAMETER_ERROR;
		}
		ContractType old = get(cType.getCode());
		if(null == old){
			return RESULT.NOT_FIND;
		}
		if(isNotNull(cType.getName())) {
			old.setName(cType.getName());
		}if(null != cType.getDeleted()) {
			old.setDeleted(cType.getDeleted());
		}
		
		RESULT result = upd(old);
		
		return result;
	}
	
	public List<ContractType> findAll(String oc) {
		List<ContractType> list = find(sql_findAll, Integer.parseInt(oc));
		return list;
	}
	
	
	public List<ContractType> findByOc(Integer oc) {
		List<ContractType> list = find(sql_findAll, oc);
		return list;
	}
	public List<ContractType> findByNameOc(String name, Integer oc){
		if (name == null || oc == null) return null;
		StringBuffer hql = new StringBuffer("FROM ContractType iat WHERE iat.name = ? AND iat.oc = ? ");
		List<Object> parm = new ArrayList<Object>();
		
		parm.add(name);
		parm.add(oc);
		
		return find(hql.toString(), parm.toArray());
	}
}
